var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var RssConstants = require('../constants/RssConstants');
var assign = require('object-assign');

var CHANGE_EVENT = 'change';

var _sources = {};

function create(source){
  var id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36);
  _sources[id] = {
    id: id,
    complete: false,
    text: source
  };
}

var SourceStore=assign({},EventEmitter.prototype,{
  /**
   * Get the entire collection of TODOs.
   * @return {object}
   */
  getAll: function() {
    return _sources;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  /**
   * @param {function} callback
   */
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  /**
   * @param {function} callback
   */
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  }
})


// Register callback to handle all updates
AppDispatcher.register(function(action) {
  var text;

  switch(action.actionType) {
    case RssConstants.RSS_SOURCE_CREATE:
      text = action.text.trim();
      if (text !== '') {
        create(text);
        SourceStore.emitChange();
      }
      break;

    default:
      // no op
  }
});

module.exports = SourceStore;
